#    GMail-Notifier - A cooler looking gmail notifier for Ubuntu
#    Copyright (C) 2009 Uday K Verma
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import gobject
import gtk.glade

import gmailnotifier.config as config
import gmailnotifier.atomreader as atomreader
import gmailnotifier.apppaths as apppaths
import gmailnotifier.sound as sound

class PrefWindow(gobject.GObject):
    __gsignals__ = { 'credentials-saved' : (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()) }
    def __init__(self):
        gobject.GObject.__init__(self)
        self.wTree = gtk.glade.XML (os.path.join (apppaths.media_path (), "ui/gmail-notify-prefs/gmail-notify-prefs.glade"))
        
        events = { 'on_button_close_clicked' : self.on_button_close_clicked,
                   'on_button_check_creds_clicked' : self.on_button_check_creds_clicked,
                   'on_save_cred_clicked' : self.on_save_cred_clicked,
                   'on_hscale_refresh_value_changed' : self.on_hscale_refresh_value_changed,
                   'on_hscale_delay_value_changed' : self.on_hscale_delay_value_changed,
                   'on_checkSound_toggled' : self.on_checkSound_toggled,
                   'on_about_clicked' : self.on_about_clicked,
                   'on_hscale_volume_format_value' : self.on_hscale_volume_format_value,
                   'on_hscale_volume_value_changed' : self.on_hscale_volume_value_changed
                   }
        
        # load and setup values
        #
        self.wTree.get_widget ("username").set_text (config.get_config ("username"))
        self.wTree.get_widget ("password").set_text (config.get_password (config.get_config ("username")))
        self.wTree.get_widget ("hscale_refresh").set_value (int(config.get_config ("refresh-interval")) * 0.001)
        self.wTree.get_widget ("hscale_delay").set_value (int(config.get_config ("message-display-interval")) * 0.001)
        self.wTree.get_widget ("checkSound").set_active (int (config.get_config ("sound-notifications-enabled")))
        self.wTree.get_widget ("hscale_volume").set_value (int (float(config.get_config ("sound-notifications-volume")) * 100))
        
        self._enableVolumeControls (int (config.get_config ("sound-notifications-enabled")))
        
        self.orig_username = self.wTree.get_widget ("username").get_text()
        self.orig_password = self.wTree.get_widget ("password").get_text()
        
        self._root_window().connect ("delete-event", self.on_window_delete)
        try:
            self._root_window().set_icon_from_file ("%s/images/gmail-icon32.png" % apppaths.media_path())
        except:
            pass # silently ignore any icon load errors
        
        self.wTree.signal_autoconnect (events)
        
    def on_window_delete(self, sender, event):
        return not self._do_close_checks ()
        
    def on_button_close_clicked (self, sender):
        if self._do_close_checks():
            self._root_window().destroy ()
            
    def on_hscale_volume_format_value (self, sender, value):
        return "%d%%" % (int(value))
        
    def on_hscale_volume_value_changed (self, sender):
        volume = self.wTree.get_widget ("hscale_volume").get_value () * 0.01

        sound.playSound ("file://%s/sounds/new-mail.wav" % (apppaths.media_path()), volume)
        config.set_config ("sound-notifications-volume", "%.2f" % (volume))
        
    def _do_close_checks (self):
        un, pw = self._get_creds ()
        if un != self.orig_username or pw != self.orig_password:
            # username or password has been changed since the last save
            #
            mb = gtk.MessageDialog (parent = self._root_window (), flags = 0,
                                    type = gtk.MESSAGE_QUESTION,
                                    message_format="The credentials have changed since the last time you saved them.\n\nDo you want to save them before you close program preferences?")
            mb.add_buttons (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                            gtk.STOCK_DISCARD, 100,
                            gtk.STOCK_SAVE, 101)
            mb.set_default_response (101)
            resp_code = mb.run ()
            mb.destroy ()
            if resp_code == gtk.RESPONSE_CANCEL:
                return False
            elif resp_code == 101:
                if self._validate_creds ():
                    self.on_save_cred_clicked (None)
                else:
                    return False
                
        return True
        
    def on_checkSound_toggled (self, sender):
        if sender.get_active ():
            config.set_config("sound-notifications-enabled", "1")
            self._enableVolumeControls (True)
        else:
            config.set_config("sound-notifications-enabled", "0")
            self._enableVolumeControls (False)
            
    def _enableVolumeControls (self, enable):
        # enable/disable the volume controls
        self.wTree.get_widget ("lblvolume").set_sensitive (enable)
        self.wTree.get_widget ("hscale_volume").set_sensitive (enable)
    
    def _root_window (self):
        return self.wTree.get_widget ("gmailnotifyprefs")
        
    def _get_creds(self):
        return (self.wTree.get_widget ("username").get_text(),
                self.wTree.get_widget ("password").get_text())
        
    def _validate_creds (self):
        username, password = self._get_creds()
        if not username or not password:
                mb = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
                                        "Please specify both username and password.")
                mb.set_title ("GMail Notify")
                mb.run ()
                mb.destroy ()
                return False
        return True
    
    def on_button_check_creds_clicked (self, sender):
        try:
            if not self._validate_creds ():
                return
            
            username, password = self._get_creds()
                
            m = atomreader.GMailAtomReader (username, password)
            m.fetchMails ()
            
            mb = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
                                    "GMail credentials test was sucessful.")
            mb.set_title ("GMail Notify")
            mb.run ()
            mb.destroy()
        except Exception, e:
            mb = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
                                    "GMail credentials failed to login.  Please make sure that you are connected to the internet and that your credentials are correct.")
            mb.set_title ("GMail Notify")
            mb.run ()
            mb.destroy()
            

    def on_save_cred_clicked (self, sender):
        if not self._validate_creds ():
            return
        
        username, password = self._get_creds ()
        
        un, pw = config.get_config ("username"), config.get_password (config.get_config("username"))
        if un != username or pw != password:
            config.set_config ("username", username)
            config.set_password (username, password)
            
            self.emit ("credentials-saved")
            
            self.orig_username, self.orig_password = username, password
    
    def on_hscale_refresh_value_changed (self, sender):
        config.set_config ("refresh-interval", str(int(self.wTree.get_widget ("hscale_refresh").get_value() * 1000)))
    
    def on_hscale_delay_value_changed (self, sender):
        config.set_config ("message-display-interval", str(int(self.wTree.get_widget ("hscale_delay").get_value() * 1000)))
        
    def on_about_clicked (self, sender):
        msg = gtk.MessageDialog (parent = self._root_window(), flags=0, type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_OK)
        msg.set_markup ('GMail-Notifier for Ubuntu\n<i>A cooler looking gmail notification application</i>\n\n(C) Copyright 2009 Uday K Verma\n(C) Copyright 2009 Ritesh Nadhani\nAll GMail icons artwork (C) Copyright IconExpo.com\n\nVisit http://soundc.de/gmail-notifier for contact information.')
        
        
        msg.set_title ('About GMail-Notifier')
        msg.run ()
        msg.destroy ()

if __name__ == "__main__":
    PrefWindow ()
    gtk.main()